package com.binge.backend.controller;

import com.alibaba.fastjson.JSONObject;
import com.binge.backend.dto.BookDto;
import com.binge.backend.entity.BookEntity;
import com.binge.backend.service.IBookshopService;
import com.binge.backend.util.ResultVo;
import com.binge.backend.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Binge
 * @desc 图书商店页面控制器类
 * @date 2020/10/17 下午5:18
 */
@RestController
@RequestMapping("/bookshop")
@Slf4j
@Api(value = "图书商店 API 接口",tags = "图书商店 API 接口")
public class BookshopController {
    @Resource
    private IBookshopService bookshopService;

    @PostMapping("/books/{pageNum}")
    @ApiOperation("获取图书")
    public ResultVo<List<BookEntity>> getBook(@PathVariable("pageNum") int pageNum,@RequestBody BookDto bookDto){
        log.info(pageNum+":"+bookDto.toString());
        List<BookEntity> books = bookshopService.getBook(bookDto,pageNum);
        return ResultVo.success(books);
    }

    @PostMapping("/find/books")
    @ApiOperation("查找图书")
    public ResultVo<List<BookEntity>> findBook(@RequestBody BookDto bookDto){
        return null;
    }

    /**
     * 购买书籍请求处理
     * @Param bookName 书名
     * @return 返回结果
     */
    @PostMapping("/buy")
    @ApiOperation("订购书籍")
    @ApiImplicitParam(name = "bookName",value = "书名")
    public ResultVo<String> buyBook(@RequestBody String bookName, HttpServletRequest request) {
        log.info(bookName);
        //解析JSON字符串
        JSONObject parse = JSONObject.parseObject(bookName);
        bookName = (String)parse.get("bookName");
        //获取Token
        String token = request.getHeader("Authorization");
        String username = TokenUtil.getLoginName(token);
        log.info(username+" : "+bookName);
        Boolean result = bookshopService.buyBook(bookName , username);
        if (result) {
            return ResultVo.success("buy ok");
        }
        return ResultVo.fail("buy fail");


    }

}
